package com.hvgroup.modules.dify.web;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hvgroup.annotation.rest.AnonymousPostMapping;
import com.hvgroup.modules.dify.service.DifyDatasetService;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.support.StandardServletMultipartResolver;
import reactor.core.publisher.Mono;

import java.util.Map;

@Slf4j
@RestController
@RequiredArgsConstructor
@Api(tags = "运维：应用管理")
@RequestMapping("/api/provider/dataset")
public class DifyDatasetController {

    private final DifyDatasetService difyDatasetService;

//    @ApiOperation(value = "查询应用")
//    @AnonymousGetMapping
//    public Mono<JsonNode> getDataset(@RequestParam(name = "url") String url,  @RequestParam Map<String, Object> params) {
//        return difyDatasetService.getDataset(url, params);
//    }



    @Bean
    public MultipartResolver multipartResolver() {
        return new StandardServletMultipartResolver();
    }

    @AnonymousPostMapping(value = "/upload",
            consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseEntity<Mono<JsonNode>> postFileset(@RequestPart(value = "meta", required = false) String metaJson,
                                                      @RequestPart("file") MultipartFile file) {
        JsonNode meta;
        try {
            meta = new ObjectMapper().readTree(metaJson);
        } catch (JsonProcessingException e) {
            log.error("meta 字段不是合法 JSON: {}", e.getMessage());
            return ResponseEntity.badRequest().body(Mono.error(e));
        }
        return ResponseEntity.ok(difyDatasetService.postFileset(meta, file));
    }

    @AnonymousPostMapping(value = "/upload2",
            consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseEntity<String> postFileset2(@RequestPart("file") MultipartFile file) {
        System.out.println("111");
        return ResponseEntity.ok("1");
    }



    // documents

    // create-by-file

    // v1/datasets/${dataset_id}/documents/${document_id}`

}
